package com.servlet;

import java.io.IOException;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bean.ReFundRequest;
import com.config.WeChatConfig;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ophiux.wechat.db.MchAppModel;
import com.ophiux.wechat.db.Mch_App_Map;
import com.ophiux.wechat.model.ReFundResponse;
import com.ophiux.wechat.utils.Sha1Util;
import com.ophiux.wechat.utils.WeChatPayUtil;
import com.utils.PayUtils;



/**
 * 退款发起
 * @author Administrator
 *前端/服务端发起退费时是否传入了APP_ID和APP_SECRET？？？？？
 */
public class ReFundServlet extends HttpServlet {

	private static Logger logger = LoggerFactory.getLogger(ReFundServlet.class);
	
	/**
	 * 退款证书地址
	 */
	private static String sslFilePath = "E:/Wechat_Cert/Wechat_CM/apiclient_cert.p12";
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		 response.setHeader("Content-type", "text/html;charset=UTF-8");
		 String subMchId=request.getParameter("subMchId");//子商户号
		 String outTradeNo=request.getParameter("outTradeNo");//商户订单号
		 String opUserId=request.getParameter("opUserId");//操作员帐号, 默认为商户号
		 String outRefundNo=request.getParameter("outRefundNo");//商户系统内部的退款单号，商户系统内部唯一，同一退款单号多次请求只退一笔 
		 String refundFee=request.getParameter("refundFee");//退款金额 
		 String totalFee=request.getParameter("totalFee");//总金额 
		 /**
		  * 商户信息,根据MchId获取
		  */
		 MchAppModel mchModel = Mch_App_Map.getMchAppModelByMchId(subMchId);
		 
		 String appid = null;
	     String appsecret = null;
	     String api_key = null;
	     /**
	      * 商户信息存在
	      */
	     if(mchModel != null){
			 appid = mchModel.getAppid();
			 appsecret = mchModel.getAppsecret();
			 api_key = mchModel.getApi_key();
		 }
	     
	     String sign=request.getParameter("sign");
	     
	     
	     logger.info("---------------------普通商户:退款请求参数------------------------------");
	     logger.info("subMchId="+subMchId
	    		 +"---outTradeNo="+outTradeNo
	    		 +"---opUserId="+opUserId
	    		 +"---outRefundNo="+outRefundNo
	    		 +"---refundFee="+refundFee
	    		 +"---totalFee="+totalFee
	    		 +"---appid="+appid
	    		 +"---appsecret="+appsecret
	    		 +"---api_key="+api_key
	    		 );
	     logger.info("----------------------普通商户:退款请求参数-----------------------------");
//		 
		String result =  WeChatPayUtil.ReFund(appid, api_key, appsecret,
				subMchId, outTradeNo, opUserId, outRefundNo, refundFee,
				totalFee, sign,sslFilePath);
		 
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}
